package com.z.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.z.sys.mapper.RoleMapper;
import com.z.sys.mapper.UserMapper;
import com.z.sys.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LoginUser loginUser = new LoginUser();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username",s));
        if(user != null){
            BeanUtils.copyProperties(user, loginUser);
            List<String> permissions = roleMapper.selectPermissionByUserId(user.getId());
            loginUser.setAuthorities(permissions.parallelStream().map(p->new SimpleGrantedAuthority(p)).collect(Collectors.toList()));
        }
        return loginUser;
    }
}